# -*- coding: utf-8 -*-

"""
@author: david
@software: PyCharm
@file: getdata.py
@time: 2021/10/12 11:23
@desc:
"""
import hashlib
import json
import os
import time
from hashlib import md5
# import data.wencai as wc
import pandas as pd
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

# import easyquotation
from data.wencai.core.crawler import Wencai


def market_volume():
    """市场量能"""

    data = {
        'UserID': '0',
        'a': 'MarketCapacity',
        'apiv': 'w29',
        'c': 'HomeDingPan',
        'Token': '0',
        'PhoneOSNew': '1',
        'Type': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("市场量能 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def limit_broke():
    """炸板股"""

    data = {
        'Order': '1',
        'a': 'DaBanList',
        'st': '100',
        'apiv': 'w28',
        'c': 'HomeDingPan',
        'PidType': '2',
        'Is_st': '1',
        # 'Day': date,
        'PhoneOSNew': '1',
        'Type': '4',
        # 'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'index': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("炸板股 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_daily_limit_performance(pid_type):
    """获取涨停表现"""

    data = {
        'Order': '0',
        'a': 'DailyLimitPerformance',
        'st': '100',
        'apiv': 'w28',
        'c': 'HomeDingPan',
        'PidType': pid_type,
        # 'Is_st': '1',
        # 'Day': date,
        'PhoneOSNew': '1',
        'Type': '4',
        # 'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'index': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取涨停表现  html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html['info']


def threePlate():
    """三连板"""

    data = {
        'Order': '0',
        'a': 'DailyLimitPerformance',
        'st': '100',
        'apiv': 'w29',
        'c': 'HomeDingPan',
        'PidType': '3',
        # 'Is_st': '1',
        # 'Day': date,
        'PhoneOSNew': '1',
        'Type': '4',
        # 'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'index': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取涨停表现  html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html['info']


def fourPlate():
    """四连板"""

    data = {
        'Order': '0',
        'a': 'DailyLimitPerformance',
        'st': '100',
        'apiv': 'w29',
        'c': 'HomeDingPan',
        'PidType': '4',
        # 'Is_st': '1',
        # 'Day': date,
        'PhoneOSNew': '1',
        'Type': '4',
        # 'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'index': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取涨停表现  html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html['info']


def fivePlate():
    """五连板"""

    data = {
        'Order': '0',
        'a': 'DailyLimitPerformance',
        'st': '100',
        'apiv': 'w29',
        'c': 'HomeDingPan',
        'PidType': '5',
        # 'Is_st': '1',
        # 'Day': date,
        'PhoneOSNew': '1',
        'Type': '4',
        # 'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'index': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取涨停表现  html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html['info']


def get_daily_limit_performance2(pid_type):
    """获取昨日涨停今日未涨停表现"""

    data = {
        'Order': '1',
        'a': 'DailyLimitPerformance2',
        'st': '100',
        'apiv': 'w28',
        'c': 'HomeDingPan',
        'PidType': pid_type,
        # 'Is_st': '1',
        # 'Day': date,
        'PhoneOSNew': '1',
        'Type': '5',
        # 'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'index': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取昨日涨停今日未涨停表现 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html['info']


def twoBoardStocksYesterday():
    """未涨停的昨日二板个股"""

    data = {
        'Order': '1',
        'a': 'DailyLimitPerformance2',
        'st': '100',
        'apiv': 'w29',
        'c': 'HomeDingPan',
        'PidType': '3',
        # 'Is_st': '1',
        # 'Day': date,
        'PhoneOSNew': '1',
        'Type': '5',
        # 'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'index': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取昨日涨停今日未涨停表现 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html['info']


def threeBoardStocksYesterday():
    """未涨停的昨日三板个股"""

    data = {
        'Order': '1',
        'a': 'DailyLimitPerformance2',
        'st': '100',
        'apiv': 'w29',
        'c': 'HomeDingPan',
        'PidType': '4',
        # 'Is_st': '1',
        # 'Day': date,
        'PhoneOSNew': '1',
        'Type': '5',
        # 'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'index': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取昨日涨停今日未涨停表现 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html['info']


def fourBoardStocksYesterday():
    """未涨停的昨日四板及以上个股"""

    data = {
        'Order': '1',
        'a': 'DailyLimitPerformance2',
        'st': '100',
        'apiv': 'w29',
        'c': 'HomeDingPan',
        'PidType': '5',
        # 'Is_st': '1',
        # 'Day': date,
        'PhoneOSNew': '1',
        'Type': '5',
        # 'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'index': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取昨日涨停今日未涨停表现 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html['info']


def get_history_date(dates='30'):
    """获取最近几个交易日的日期"""

    data = {
        # 'StockID': 'SH000001',
        'a': 'GetMoneyDate',
        'st': dates,
        'apiv': 'w27',
        'c': 'Emotion',
        # 'UserID': '0',
        # 'Is_st': '1',
        # 'Day': date,
        'PhoneOSNew': '1',
        # 'Type': '6',
        # 'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'index': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphis.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取最近几个交易日的日期 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    data = []
    for m_data in html['ZY']:
        data.append(m_data['Day'])
    # print('get_history_date', data)
    return data


def get_last_date():
    """获取最近的一个交易日的日期"""

    data = {
        'StockID': 'SH000001',
        'a': 'GetZsPanKou',
        'st': '200',
        'apiv': 'w27',
        'c': 'StockL2Data',
        'UserID': '0',
        'Is_st': '1',
        # 'Day': date,
        'PhoneOSNew': '1',
        'Type': '6',
        'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取最近的一个交易日的日期 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    html = time.strftime("%Y-%m-%d", time.localtime(html['real']['time']))
    return html


def get_history_trend(code, date):
    """获取股票历史分时数据"""

    data = {
        'StockID': code,
        'a': 'GetStockTrend',
        'st': '200',
        'apiv': 'w28',
        'c': 'StockL2History',
        'UserID': '0',
        'Is_st': '1',
        'Day': date,  # 20211229
        'PhoneOSNew': '1',
        'Type': '6',
        'Token': '0',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphis.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取股票历史分时数据 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    if html['errcode'] != '0':
        print(html)
        return None
    return html


def get_today_trend(code):
    """获取股票今日分时数据
    :type code: 603011
    """

    data = {
        'a': 'GetStockVolTurIncremental',
        'UserID': '0',
        'apiv': 'w27',
        'c': 'StockL2Data',
        'PhoneOSNew': '1',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'StockID': code,
        'Token': '0',
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取股票今日分时数据 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


# def get_data_easyquotation(stock_code):
#     """获取股票数据"""
#     quotation = easyquotation.use("qq")  # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
#     data = quotation.stocks(stock_code)  # quotation.stocks(['000001', '162411']) 多只股票
#     if data is None:
#         return
#
#     return data


def get_data():
    """选股宝涨速板块(3)"""

    data = {
        # 'Order': "1",
        'a': 'ZhangFuDetail',
        # 'st': '200',
        'apiv': 'w27',
        'c': 'HomeDingPan',
        # 'Index': '0',
        # 'Is_st': '1',
        # 'PidType': '1',
        # 'PhoneOSNew': '1',
        # 'Type': '6',
        # 'Token': 'bae452681628d6e8d5986ad81eede16a',
        'PhoneOSNew': '1',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("选股宝涨速板块 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_now_limit():
    """获取现在涨停的股票池"""

    data = {
        'Order': "1",
        'a': 'DaBanList',
        'st': '200',
        'apiv': 'w27',
        'c': 'HomeDingPan',
        'Index': '0',
        'Is_st': '1',
        'PidType': '1',
        'PhoneOSNew': '1',
        'Type': '6',
        # 'Token': 'bae452681628d6e8d5986ad81eede16a',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取现在涨停的股票池 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_history_limit(day):
    """获取历史涨停的股票池"""

    data = {
        'Order': "1",
        'st': '200',
        'a': 'HisDaBanList',
        'c': 'HisHomeDingPan',
        'PhoneOSNew': '1',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'Index': '0',
        'Is_st': '1',
        'PidType': '1',
        'apiv': 'w27',
        'Type': '6',
        'Day': day  # 2021-10-25

    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphis.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as error:
        # print(day+"获取历史涨停的股票池 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(error)
        return None
    return html


def get_history_broke(day):
    """获取历史炸板的股票池"""

    data = {
        'Order': "1",
        'st': '200',
        'a': 'HisDaBanList',
        'c': 'HisHomeDingPan',
        'PhoneOSNew': '1',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'Index': '0',
        'Is_st': '1',
        'PidType': '2',
        'apiv': 'w28',
        'Type': '4',
        'Day': day  # 2021-10-25

    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphis.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取历史炸板的股票池 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_history_down_limit(day):
    """获取历史跌停的股票池"""

    data = {
        'Order': "1",
        'st': '200',
        'a': 'HisDaBanList',
        'c': 'HisHomeDingPan',
        'PhoneOSNew': '1',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'Index': '0',
        'Is_st': '1',
        'PidType': '3',
        'apiv': 'w27',
        'Type': '6',
        'Day': day  # 2021-10-25

    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphis.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取历史跌停的股票池 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_history_continue_to_harden():
    """获取昨日连板的股票池"""

    data = {
        'Order': "1",
        'st': '200',
        'a': 'ZhiShuStockList_W8',
        'c': 'ZhiShuRanking',
        'PhoneOSNew': '1',
        'old': '1',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'IsZZ': '0',
        'Token': '0',
        'Index': '0',
        'Is_st': '1',
        'PidType': '1',
        'apiv': 'w27',
        'Type': '8',
        'UserID': '0',
        'PlateID': '801902',

    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取昨日连板的股票池 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_history_continue_to_harden():
    """获取昨日连板的股票池"""

    data = {
        'Order': "1",
        'st': '200',
        'a': 'ZhiShuStockList_W8',
        'c': 'ZhiShuRanking',
        'PhoneOSNew': '1',
        'old': '1',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000',
        'IsZZ': '0',
        'Token': '0',
        'Index': '0',
        'Is_st': '1',
        'PidType': '1',
        'apiv': 'w27',
        'Type': '8',
        'UserID': '0',
        'PlateID': '801902',

    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取昨日连板的股票池 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_jihejingjia_limit():
    """获取集合竞价股票池"""

    data = {
        'Order': "1",
        'a': 'DaBanList',
        'st': '300',
        'apiv': 'w26',
        'c': 'HomeDingPan',
        'Index': '0',
        'Is_st': '1',
        'PidType': '1',
        'PhoneOSNew': '1',
        'Type': '18',
        'PidType': '8',
        'DeviceID': 'ffffffff-fade-f24e-f9d3-785f00000000'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取集合竞价股票池 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def decode(data):
    """解析数据"""
    if data is not None:

        return {
            'date': data['date'],  # 日期
            'time': data['time'],  # 时间戳
            'DieTing': data['DT'],  # 跌停数量
            'ShiJiDieTing': data['SJDT'],  # 实际跌停(去掉ST和未开板次新股)
            'ZhangTing': data['ZT'],  # 涨停数量
            'ShiJiZhangTing': data['SJZT'],  # 实际涨停(去掉ST和未开板次新股)
            'ShangZhangJiaShu': data['SZJS'],  # 上涨家数
            'XiaDieJiaShu': data['XDJS'],  # 下跌家数
        }
    else:
        return None


def __get_data_kpl_plate_code__(stock, theme):
    """获取所属题材的代码
    :param theme: str
    :type stock: str
    :return jx: str, 所属题材的代码
    """

    data = {
        'a': 'GetStockIDPlate',
        'apiv': 'w25',
        'Type': '2',
        'c': 'StockL2Data',
        'PhoneOSNew': '1',
        'DeviceID': '00000000-65e3-f053-ffff-ffffda3e1656',
        'Token': '0',
        'UserID': '0',
        'StockID': stock
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        # print(json.loads(html))

        # for L in json.loads(html)['List']:
        #     print(L)

        for jx in json.loads(html)['ListJX']:
            # print(jx)
            if jx[1] == theme:
                # print(jx[0])
                return jx[0]
    except Exception as spider_error:
        # print("获取所属题材的代码 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None


def get_plate_list_stock(stock, plate_name):
    """获取题材的股票池"""
    plate_stock = __get_data_kpl_plate_code__(stock, plate_name)
    data = {
        'Order': '1',
        'str': '30',
        'a': 'ZhiShuStockList_W8',
        'c': 'ZhiShuRanking',
        'PhoneOSNew': '1',
        'old': '1',
        'DeviceID': '00000000-65e3-f053-ffff-ffffda3e1656',
        'Token': '0',
        'Index': '0',
        'apiv': 'w25',
        'Type': '6',
        'UserID': '0',
        'PlateID': plate_stock
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取题材的股票池 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_trend(stock):
    """获取大盘分时数据"""
    data = {
        'a': 'GetZstrend',
        'apiv': 'w27',
        'c': 'StockL2Data',
        'StockID': stock,
        'PhoneOSNew': '1',
        'UserID': '0',
        'DeviceID': '14779fc5-7a53-343c-ba93-1d063c51181e',
        'Token': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取大盘分时数据 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_stock_trend(stock):
    """获取个股分时数据"""
    data = {
        'a': 'GetStockBsvolumeIncremental',
        'apiv': 'w27',
        'c': 'StockL2Data',
        'StockID': stock,
        'PhoneOSNew': '1',
        'UserID': '0',
        'DeviceID': '14779fc5-7a53-343c-ba93-1d063c51181e',
        'Token': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://apphq.longhuvip.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取个股分时数据 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_k_line(stock):
    """获取大盘K线数据"""
    data = {
        'a': 'GetZhiShuKLine',
        'st': '630',
        'apiv': 'w27',
        'Type': 'd',
        'c': 'ZhiShuKLine',
        'StockID': stock,
        'PhoneOSNew': '1',
        'UserID': '0',
        'DeviceID': '14779fc5-7a53-343c-ba93-1d063c51181e',
        'Token': '0',
        'Index': '0'
    }

    # 构造URL请求、user-agent头文件
    url = 'https://his.kaipanla.com/w1/api/index.php'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False).text
        html = json.loads(html)
    except Exception as spider_error:
        # print("获取大盘K线数据 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_timestamp_cailianshe():
    """获取时间戳"""
    data = _get_data('https://www.cls.cn/telegraph')
    _data = data.find('ctime')
    __data = data[_data + 7:_data + 17]  # 获取时间戳
    return __data


def _get_data(url):
    """获取网络数据"""
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0'}
    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    try:
        html = session.get(url=url, headers=headers, verify=False).text
        # html = json.loads(html)
    except Exception as spider_error:
        # print("获取网络数据 html抓取过程报错，错误信息为：%s" % spider_error)
        raise ValueError(spider_error)
        return None
    return html


def get_data_cailianshe(timestamp):
    """财联社数据
    :type timestamp: str，时间戳
    """

    url = 'https://www.cls.cn/nodeapi/updateTelegraphList?'
    decode_in = 'app=CailianpressWeb&category=&hasFirstVipArticle=1&lastTime=' + timestamp + '&os=web&rn=20&subscribedColumnIds=&sv=7.5.5'
    decode_out = Decode().decode(decode_in)
    data = _get_data(url + decode_in + '&sign=' + decode_out)
    # print(url + decode_in + '&sign=' + decode_out)
    __data = timestamp
    lists = []
    if data is not None:
        try:
            data = json.loads(data)
            _data = data['data']['roll_data']
            if len(_data) > 0:
                print(url + decode_in + '&sign=' + decode_out)
                __data = str(_data[0]['ctime'])  # 时间戳
                # print(__data)
                for m in _data:
                    lists.append([str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(m['ctime']))), m['content'],
                                  m['stock_list']])
                    # print(m['content'])
                    # print(m['content'].find(' '))
        except Exception as spider_error:
            # print(spider_error)
            raise ValueError(spider_error)
    return __data, lists


class Decode:
    def use_sha(self, text):
        if not isinstance(text, bytes):
            text = bytes(text, 'utf-8')
        sha = hashlib.sha1(text)
        encrypts = sha.hexdigest()
        return encrypts

    def md5value(self, s):
        a = md5(s.encode()).hexdigest()
        return a

    def decode(self, s):
        return self.md5value(self.use_sha(s))


def wencai_search(query):
    print(query)
    file = './data/wencai/data/' + query + '.xlsx'
    if os.path.exists(file):
        result = pd.DataFrame(pd.read_excel(file, converters={'code': str}))
    else:
        time.sleep(3)  # 频繁刷新会封IP
        # 添加代理
        # proxy = '127.0.0.1:7890'
        # proxies = {
        #     'http': 'http://' + proxy,
        #     'https': 'https://' + proxy,
        # }
        # wencai = Wencai(proxies=proxies)
        wencai = Wencai()
        count = 6
        while count > 0:
            count = count - 1
            result = wencai.search(query)
            if result is not None:
                result.to_excel(file, index=False)
                break
            time.sleep(3)
        if count == 1:
            raise ValueError('问财查询失败')
    return result


if __name__ == '__main__':
    print(get_history_date())
    # print(wencai_search('当日涨幅大于0'))
